* distance to closest public transit stations in each census tract
********************************************************************************
* prelims
********************************************************************************
{
clear all
set more off
cap log close

}
********************************************************************************	
* closest stations
********************************************************************************
{
* closest tran/subway station
use "$data/int/distance_stations_tract.dta", clear

* drop unnecessary variables
drop AREA

* reshape long
gather METRO3107V-FGCPCRE36V

* rename
rename value Distance
rename variable StationID

* only keep the 15 closest stations per tract
sort ID Distance
bys ID: egen StatRank = rank(Distance), unique
keep if StatRank<=15

* identify transportation in station
g Metro = (regexm(StationID,"METRO")==1)
g FGC = (regexm(StationID,"^FGC")==1)
g Renfe = (regexm(StationID,"^ADIF")==1)
g Tram = (regexm(StationID,"^TRAM")==1)
g Funicular = (regexm(StationID,"^XF")==1)

g Type = "Metro" if Metro==1
replace Type = "FGC" if FGC==1
replace Type = "Renfe" if Renfe==1
replace Type = "Tram" if Tram==1
replace Type = "Funicular" if Funicular==1

drop Metro-Funicular

* reshape wide
reshape wide StationID Distance Type, i(ID DISTRICTE BARRI AEB SEC_CENS GRANBARRI ZUA LITERAL) j(StatRank)

* rename
rename DISTRICTE CDIS
rename SEC_CENS CSEC

gsort ID CDIS CSEC - Distance1
duplicates drop CDIS CSEC, force

* mean distance - closest three stations
forval i = 1(1)3 {
	bys BARRI: egen MeanD`i' = mean(Distance`i')
	la var MeanD`i' "distance to #`i' closest station"
}

* store
compress
save "$data/int/distance_trans.dta", replace
}
********************************************************************************	
* closing
********************************************************************************
{
cap log close
clear
}
